package com.hongmeng.teamwork.factory.attachment;

import com.hongmeng.teamwork.entity.dto.AttachmentDto;
import com.hongmeng.teamwork.enums.AttachmentEnum;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
@Component
public class AttachmentFactory implements InitializingBean {

    @Resource
    private List<AttachmentHandler> attachmentHandlerList;
    private final Map<AttachmentEnum, AttachmentHandler> handlerMap = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        for (AttachmentHandler attachmentHandler : attachmentHandlerList) {
            handlerMap.put(attachmentHandler.getEnum(), attachmentHandler);
        }
    }

    public String upload(AttachmentDto attachmentDto) {
        String attachmentKey;
        try {
            attachmentKey = handlerMap.get(AttachmentEnum.ofEnum(attachmentDto.getAttachmentType()))
                    .upload(attachmentDto);
        } catch (Exception e) {
            log.error("AttachmentFactory.upload.error: {}", e.getMessage(), e);
            throw new RuntimeException("附件上传失败！");
        }
        return attachmentKey;
    }
}
